import { ClearnEmpryProp } from "@/tools";
import axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse } from "axios";
import { PassCodeList, whiteList, } from './config'

import { StandardResponse } from "@/api";
const envObj = import.meta.env
const axiosDefaultConfig: AxiosRequestConfig = {
  baseURL: envObj.VITE_SERVER_API_BASE,
  /* headers: {
    'Content-Type': 'application/json; charset=utf-8'
  } */
}
const COMMON_SERVER: AxiosInstance = axios.create(axiosDefaultConfig)
/**
 * 发送服务器请求前,在请求头中添加token
 */
COMMON_SERVER.interceptors.request.use(async config => {
  const { data, url, method } = config
  if (envObj.DEV) {
    console.log(method, url, data);
  }
  if (data instanceof FormData) { return config }
  // 白名单无需处理
  if (!whiteList.includes(config.url!)) {
    console.warn('检测到非白名单接口使用非加密请求')
  }
  const clearnData = ClearnEmpryProp(data || {})
  if (envObj.VITE_ENABLE_API_APPEND_TIMESTAMP === 'ENABLE') {
    Object.assign(clearnData, { t: Date.now() })
  }
  config.data = clearnData
  return config
}, error => {
  return Promise.reject(error)
})
COMMON_SERVER.interceptors.response.use(async (response: AxiosResponse<StandardResponse<any>>) => {

  const { code, message, data } = response.data

  // 出现异常
  if (!PassCodeList.includes(code)) return Promise.reject(message)
  // 白名单不需要加解密
  if (!whiteList.includes(response.config.url!)) {
    console.warn('非白名单接口使用非加密请求工具,响应内容', data)
  }
  return data
}, (error) => {
  console.error(error);
  const { response } = error
  const { data, status } = response || {}

  if (status.toString().startsWith('5')) return Promise.reject(data?.message || '服务器出错了QAQ~')
  return Promise.reject(error)
})
export { COMMON_SERVER }

